/* 
 * File:   CInetAddress.h
 * Author: faraj
 *
 * Created on September 15, 2009, 3:41 AM
 */

#ifndef _CINETADDRESS_H
#define	_CINETADDRESS_H

#include "CWrapper.h"
#include <netdb.h>
#include <ctype.h>

class CInetAddress
{
private:
    
    string address;
    int port;
    struct sockaddr_in *addr;
    bool error;
    
public:
    
    CInetAddress(string inetAdd, int prt)
    {
        port = prt;
        addr = new sockaddr_in();
        bzero(addr,sizeof(*addr));
        
        addr->sin_family = AF_INET;
        addr->sin_port = htons(port);
        
        char *cbuff = new char[16];
        
        if ( isdigit(*inetAdd.c_str()) )
	{	
            addr->sin_addr.s_addr = inet_addr(inetAdd.c_str());
            
            error = !Inet_pton(AF_INET,inetAdd.c_str(),&addr->sin_addr);
            address = inetAdd;
	}
        else
        {
            struct hostent *HostData;
            HostData = gethostbyname(inetAdd.c_str());
            
            if ( HostData == NULL )
            {
                error = true;
            }
            else
            {
                addr->sin_addr = *((struct in_addr *) HostData->h_addr);
                addr->sin_family = AF_INET;
                addr->sin_port = htons(port);
                
                char buff[16];
                
                error = !Inet_ntop(AF_INET,&(addr->sin_addr.s_addr),buff,sizeof(buff));
                address ="";
                address += buff;
                
            }
        }
    }

    CInetAddress(sockaddr_in* addrx)
    {
        addr = addrx;
        char buff[16];
        Inet_ntop(AF_INET,&(addrx->sin_addr),buff,sizeof(buff));
        address ="";
        address += buff;
        port = ntohs(addrx->sin_port);
        error = false;
    }

    bool havingError()
    {
        return error;
    }
    int getPort()
    {
        return port;
    }

    string* getAddress()
    {
        return &address;
    }

    sockaddr_in* getSockaddr_in()
    {
        return addr;
    }


    sockaddr* getSockaddr()
    {
        return (SA*) getSockaddr_in();
    }
};


#endif	/* _CINETADDRESS_H */

